﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PServiceBus.Core.Runtime.Gateway;
using Phoenix.RedisConnectors;
using PServiceBus.Gateway.Interfaces;
using PServiceBus.Gateway.Redis.DTO;
using PServiceBus.Gateway.Redis.Commands;
using PServiceBus.Gateway.Interfaces.DTO;
using PServiceBus.Gateway.Interfaces.Commands;
using PServiceBus.Core.Runtime;

namespace PServiceBus.Gateway.Redis {
    public sealed class RedisBusRouter : IBusRouter {

        private RedisSender _client;

        public RedisBusRouter() { }

        public RedisBusRouter(string address) {
            var endpoint = EndpointUri.Parse(address);
            _client = new RedisSender(RedisConstants.RPCServiceName, endpoint.Host, endpoint.Port);
        }

        #region IBusRouter Members

        public ServiceInfo[] GetServices() {
            return _client.Send<RedisRouterRequest,RedisServiceInfos>(RedisRouterRequest.Empty).Services;
        }

        public void SetConnectedClients(Guid id, bool decrement) {
            _client.Send<RouterMessage>(RedisRouterMessage.New(id: id, decrement: decrement, async: false));
        }

        public void DeleteService(Guid id) {
            _client.Send<RouterMessage>(RedisRouterMessage.New(id: id, async: false));
        }

        public IBusRouter Init(string address) {
            return new RedisBusRouter(address);
        }

        #endregion

        #region IDisposable Members

        public void Dispose() {
            try {
                if (_client != null) _client.Dispose();
                _client = null;
            } catch { }
        }

        #endregion
    }
}
